﻿using System;
using System.Security;
using System.Windows;

namespace MS.Common
{
    /// <summary>
    /// 弹出窗口
    /// </summary>
    public class CSubWindowBase : CWindowBase
    {
        /// <summary>
        /// 弹出窗口
        /// </summary>
        public CSubWindowBase()
        {
            this.AllowsTransparency = true;
            this.WindowStyle = WindowStyle.None;
            this.ShowInTaskbar = false;
            this.ResizeMode = ResizeMode.NoResize;
            this.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            this.SetResourceReference(Window.StyleProperty, "KsyWinStyle_OnlyClose");
            this.Background = System.Windows.Media.Brushes.White;
        }

        /// <summary>
        /// 打开一个窗口，并且仅在新打开的窗口关闭后才返回
        /// </summary>
        /// <returns></returns>
        [SecurityCritical]
        public new bool? ShowDialog()
        {
            try
            {
                if (this.Owner == null && this.GetHashCode() != Application.Current.MainWindow.GetHashCode())
                {
                    this.Owner = Application.Current.MainWindow;
                }

                ShowMask();

                return base.ShowDialog();
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        protected void ShowMask()
        {
            System.Windows.Shapes.Rectangle bgRectangle = GetRectangle();
            if (bgRectangle == null)
            {
                return;
            }
            bgRectangle.Visibility = Visibility.Visible;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnClosed(EventArgs e)
        {
            RemoveMask();
            base.OnClosed(e);
        }


        /// <summary>
        /// 
        /// </summary>
        protected void RemoveMask()
        {
            System.Windows.Shapes.Rectangle bgRectangle = GetRectangle();
            if (bgRectangle == null)
            {
                return;
            }
            bgRectangle.Visibility = Visibility.Collapsed;
        }

        /// <summary>
        /// 获取主窗口的矩形
        /// </summary>
        /// <returns></returns>
        private System.Windows.Shapes.Rectangle GetRectangle()
        {
            if (this.Owner == null)
            {
                return null;
            }
            try
            {
                System.Windows.Shapes.Rectangle bgRectangle = VisualTreeTool.GetChildObjects<System.Windows.Shapes.Rectangle>(this.Owner, typeof(System.Windows.Shapes.Rectangle), "bgRectangle");
                if (bgRectangle == null)
                {
                    return null;
                }
                return bgRectangle;
            }
            catch
            {
                return null;
            }
        }
    }
}
